<template>
  <layout-content header="Ingresses">
    <div style="float: left">
      <el-button
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: 'networking.k8s.io',
          resource: 'ingresses',
          verb: 'create'
        }"
        type="primary"
        size="small"
        @click="onHandleCreate(true)"
      >
        YAML
      </el-button>
      <el-button
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: 'networking.k8s.io',
          resource: 'ingresses',
          verb: 'create'
        }"
        type="primary"
        size="small"
        @click="onHandleCreate()"
      >
        {{ $t("commons.button.create") }}
      </el-button>
      <el-button
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: 'networking.k8s.io',
          resource: 'ingresses',
          verb: 'delete'
        }"
        type="primary"
        size="small"
        :disabled="selections.length === 0"
        @click="confirmDelete()"
      >
        {{ $t("commons.button.delete") }}
      </el-button>
    </div>
    <complex-table
      v-model:selects="selections"
      v-loading="uiState.loading"
      :data="srcList"
      :pagination-config="query.paginationConfig"
      :search-config="query.searchConfig"
      @search="reloadResourceList"
    >
      <el-table-column type="selection" fix />
      <el-table-column
        :label="$t('commons.table.name')"
        prop="metadata.name"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-button link type="primary" @click="onHandleViewDetails(row)">
            {{ row.metadata.name }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.namespace.namespace')"
        prop="metadata.namespace"
      />
      <el-table-column
        :label="$t('business.network.target')"
        prop="metadata.rules"
        min-width="200px"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <div v-for="(rule, index) in row.spec.rules" :key="index">
            <div v-for="(path, index) in rule.http.paths" :key="index">
              <el-link
                v-if="row.spec.tls"
                class="span-link"
                :href="'https://' + rule.host + (path.path ? path.path : '')"
                target="_blank"
              >
                {{ "https://" + rule.host + (path.path ? path.path : "") }}
              </el-link>
              <el-link
                v-if="!row.spec.tls"
                class="span-link"
                :href="'http://' + rule.host + (path.path ? path.path : '')"
                target="_blank"
              >
                {{ "http://" + rule.host + (path.path ? path.path : "") }}
              </el-link>

              <el-link
                class="span-link"
                @click="onHandleViewServiceDetails(row, path.backend)"
              >
                {{ getService(path.backend) }}:{{ getPort(path.backend) }}
              </el-link>
            </div>
          </div>
          <el-button
            v-if="row.spec.rules.length > 3"
            type="text"
            @click="onHandleViewMore(row)"
          >
            {{ $t("commons.button.show_more") }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('commons.table.created_time')"
        prop="metadata.creationTimestamp"
        min-width="40px"
        fix
      >
        <template #default="{ row }">
          {{ getAge(row.metadata.creationTimestamp) }}
        </template>
      </el-table-column>
      <ko-table-operations
        :buttons="options.buttons"
        :label="$t('commons.table.action')"
      />
    </complex-table>

    <el-dialog
      v-model="options.showMoreDialog"
      :title="$t('business.network.target')"
      width="50%"
    >
      <div v-if="options.activeIngress">
        <div
          v-for="(rule, index) in options.activeIngress.spec.rules"
          :key="index"
        >
          <div v-for="(path, index) in rule.http.paths" :key="index">
            <el-link
              class="span-link"
              :href="'http://' + rule.host + (path.path ? path.path : '')"
              target="_blank"
            >
              {{ "http://" + rule.host + (path.path ? path.path : "") }}
            </el-link>

            <el-link
              class="span-link"
              @click="
                onHandleViewServiceDetails(options.activeIngress, path.backend)
              "
            >
              {{ getService(path.backend) }}:{{ getPort(path.backend) }}
            </el-link>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="options.showMoreDialog = false">
            {{ $t("commons.button.cancel") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </layout-content>
</template>

<script setup lang="ts">
import LayoutContent from "@/views/domain/kubeHud/views/components/layout/LayoutContent.vue";
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import KoTableOperations from "@/views/domain/kubeHud/views/components/ko-table-operations/index.vue";
// import { downloadYaml } from "@/utils/actions";
// import { deleteIngress, getIngress, listIngresses } from "@/api/ingress";
// import { mixin } from "@/utils/resourceRoutes";
// import { checkPermissions } from "@/utils/permission";
// import { checkApi } from "@/utils/apis";
// import { get } from "@/utils/object";
import { useI18n } from "vue-i18n";
import {
  Ingress,
  IngressBackend,
  useK8SApi
} from "@/views/domain/kubeHud/api/k8s";
import {
  useBaseCRUDProvider,
  useBaseCRUDRoute
} from "@/views/domain/kubeHud/api/provider/baseListProvider";
import { reactive } from "vue";
import { KRouteIngress, KRouteService } from "@/views/domain/kubeHud/router";
import { getAge, getObjectFromKey } from "@/views/domain/kubeHud/utils";
import { checkPermissions } from "@/views/domain/kubeHud/utils/permission";

type Prop = {};
const props = defineProps<Prop>();

const { t } = useI18n();
const { ingressRepo } = useK8SApi();

const {
  selections,
  srcList,
  query,
  router,
  uiState,
  downloadSourceAsYaml,
  getResourceDetails,
  getResourceList,
  updateResource,
  deleteResource,
  confirmDelete,
  reloadResourceList
} = useBaseCRUDProvider({
  request: {
    getDetailsReq: ingressRepo.getIngressDetail,
    getListReq: ingressRepo.getIngress,
    updateReq: ingressRepo.updateIngress,
    deleteReq: ingressRepo.deleteIngress,
    createReq: ingressRepo.createIngress
  }
});

const { pushTo } = useBaseCRUDRoute({ router });

const options = reactive({
  showMoreDialog: false,
  activeIngress: undefined as Ingress | undefined,
  buttons: [
    {
      label: t("commons.button.edit"),
      icon: "el-icon-edit",
      click: row => {
        pushTo(KRouteIngress.Edit, {
          namespace: row.metadata.namespace,
          name: row.metadata.name
        });
      },
      disabled: () => {
        return !checkPermissions({
          scope: "namespace",
          apiGroup: "networking.k8s.io",
          resource: "ingresses",
          verb: "update"
        });
      }
    },
    {
      label: t("commons.button.edit_yaml"),
      icon: "el-icon-edit",
      click: row => {
        pushTo(KRouteIngress.Edit, {
          namespace: row.metadata.namespace,
          name: row.metadata.name,
          yaml: "true"
        });
      },
      disabled: () => {
        return !checkPermissions({
          scope: "namespace",
          apiGroup: "networking.k8s.io",
          resource: "ingresses",
          verb: "update"
        });
      }
    },
    {
      label: t("commons.button.download_yaml"),
      icon: "el-icon-download",
      click: row => {
        downloadSourceAsYaml(row);
      }
    },
    {
      label: t("commons.button.delete"),
      icon: "el-icon-delete",
      click: row => {
        confirmDelete(row);
      },
      disabled: () => {
        return !checkPermissions({
          scope: "namespace",
          apiGroup: "networking.k8s.io",
          resource: "ingresses",
          verb: "delete"
        });
      }
    }
  ]
});

const getService = (backend: IngressBackend) => {
  return backend.service?.name ?? "";
};

const getPort = (backend: IngressBackend) => {
  return backend.service?.port?.number ?? "";
};

const onHandleCreate = (yaml?: boolean) => {
  pushTo(KRouteIngress.Create, { yaml: yaml ? "true" : "false" });
};

const onHandleViewMore = (row: Ingress) => {
  options.activeIngress = row;
  options.showMoreDialog = true;
};

const onHandleViewDetails = (row: Ingress) => {
  pushTo(KRouteIngress.Details, {
    namespace: row.metadata.namespace,
    name: row.metadata.name
  });
};

const onHandleViewServiceDetails = (row: Ingress, backend: IngressBackend) => {
  pushTo(KRouteService.Details, {
    namespace: row.metadata.namespace,
    name: backend.service?.name
  });
};
</script>

<style scoped></style>
